package lessons.no6;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * TreeSet 定制排序
 */
public class N6_5_3 {
    public static void main(String[] args) {
		N6_5_3 myclass = new N6_5_3();

		//myclass.testTreeSet1();
		myclass.testTreeSet2();
		//myclass.testTreeSet3();
	}

	// 定义比较器实现Comparator接口
	class MyComparator implements Comparator {  
		public int compare(Object obj1, Object obj2) {  // 定制排序方式
		String s1 = (String) obj1;
		String s2 = (String) obj2;
		int temp = s1.length() - s2.length();
		return temp;
	}
	}
	public void testTreeSet1()
	{
		
		// 1、创建集合时，传入Comparator接口实现定制排序规则
		TreeSet<String> ts = new TreeSet<String>(new MyComparator());
		ts.add("Jack");
		ts.add("Helena");
		ts.add("Eve");
		System.out.println(ts);
		

		 
		// 2、创建集合时，使用Lambda表达式定制排序规则
		TreeSet ts2 = new TreeSet((obj1, obj2) -> {
			String s1 = (String) obj1;
			String s2 = (String) obj2;
			return s1.length() - s2.length();
		});
		ts2.add("Jack");
		ts2.add("Helena");
		ts2.add("Eve");
		System.out.println(ts2);
		
	}

	public void testTreeSet2()
	{
		TreeSet<TestA> t2 = new TreeSet<TestA>(new AComparator());

		t2.add(new TestA("123",14));
		t2.add(new TestA("123w",24));
		t2.add(new TestA("123e",10));
		t2.add(new TestA("123r",15));

		System.out.println(t2);

	}

	public void testTreeSet3()
	{
		TreeSet<TestA> t2 = new TreeSet<TestA>(new Comparator2());

		t2.add(new TestA("123",14));
		t2.add(new TestA("123w",24));
		t2.add(new TestA("123e",10));
		t2.add(new TestA("123r",15));

		System.out.println(t2);
	}
}



class AComparator implements Comparator {

	@Override
	public int compare(Object arg0, Object arg1) {
		// TODO Auto-generated method stub
		TestA s1 = (TestA) arg0;
		TestA s2 = (TestA) arg1;
		int temp = s1.age - s2.age;
		return temp;
	}  
	
}

class TestA
{
	public String name;
	public int age;

	public TestA(String name,int age)
	{
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "name:"+name+"  age:"+age;
	}

	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return age;
	}
}


class Comparator2 implements Comparator
{

	@Override
	public int compare(Object arg0, Object arg1) {
		// TODO Auto-generated method stub
		return arg0.hashCode()-arg1.hashCode();
	}
	
}

class Comparator3 implements Comparator
{

	@Override
	public int compare(Object arg0, Object arg1) {
		// TODO Auto-generated method stub
		return arg1.hashCode()-arg0.hashCode();
	}
	
}


